package com.ws.config.config;

import cn.hutool.core.exceptions.ExceptionUtil;
import cn.hutool.core.util.StrUtil;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@ControllerAdvice
public class ExceptionConfiguration {

    /**
     * 拦截捕捉自定义异常 MyException.class
     * @param ex
     * @return
     */
    @ResponseBody
    @ExceptionHandler(value = Exception.class)
    public Map<String,Object> myExceptionHandler(HttpServletRequest request, HttpServletResponse response, Exception ex) throws IOException {
        response.sendError(500,ex.getMessage());
        ex.printStackTrace();


        /*异常日志*/
        String query=request.getQueryString();
        if(StrUtil.isEmpty(query)){
            query="";
        }else{
            query="?"+query;
        }
        String url=request.getRequestURL()+query;
        String message=ExceptionUtil.stacktraceToString(ex,20000);
        //发生异常进行日志记录，写入数据库或者其他处理，此处省略
        return null;
    }

}
